package com.itlong.cloud.property;

import com.itlong.cloud.POJO.DTO.property.UserDeviceAuthAddreddDTO;
import com.itlong.cloud.POJO.PO.TimeTaskAuthDeviceAddressInfoPO;
import com.itlong.cloud.POJO.VO.property.EquipAuthUserGetVO;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.DeviceAuthEnum;
import com.itlong.cloud.equip.property.IPropertyDeviceAuthServiceClient;
import com.itlong.cloud.equip.property.IPropertyEquipServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.property.IPropertyHouseHoldInfoServiceClient;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <desc>
 *      设备地址变更刷新用户权限定时任务
 * </desc>
 *
 * @createDate 2018/2/7
 */
@EnableScheduling // 启用定时任务
@RestController
public class DeviceAddrChangeFreshAuthTimedTask {

    private static Logger LOG = LoggerFactory.getLogger(DeviceAddrChangeFreshAuthTimedTask.class);

    private static boolean deviceAddrChangeFreshAuthFirstStart = true;  //首次启动

    private static boolean isWorking;

    //设备权限接口服务
    @Autowired
    IPropertyDeviceAuthServiceClient iPropertyDeviceAuthServiceClient;

    @Autowired
    IPropertyHouseHoldInfoServiceClient iPropertyHouseHoldInfoServiceClient;

    //物业设备服务层暴露接口
    @Autowired
    IPropertyEquipServiceClient iPropertyEquipServiceClient;



    @Scheduled(cron = "30 0/5 * * * ?")  //每5分钟执行一次
//    @Scheduled(cron = "0 * * * * ?") // 每1分钟执行一次
    public void scheduler() {
        try {
            isWorking = iPropertyDeviceAuthServiceClient.getDeviceAuthTimeTaskExexuterStatus();
            if (deviceAddrChangeFreshAuthFirstStart) {
                isWorking = false;
            }
            //首次启动时无条件直接进入定时任务
            String handlerTime = DateUtil.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss");
            if (isWorking) {
//                LOG.info("【定时任务】设备地址变更刷新用户权限定时任务，正在执行：" + handlerTime);
                return;
            }
            iPropertyDeviceAuthServiceClient.updateDeviceAuthTimeTaskExexuterStatus(true);
            Map<String, Object> params = new HashMap<>();
            params.put("status", DataStatusEnum.NORMAL.getType());
            List<TimeTaskAuthDeviceAddressInfoPO> addrPOList = iPropertyDeviceAuthServiceClient.getNotFreshAddrByParams(params);
//            LOG.info("【定时任务】设备地址变更刷新用户权限定时任务，当前时间：" + handlerTime + " 所影响的小区地址size：" + addrPOList.size());
            if (addrPOList != null && !addrPOList.isEmpty()) {
                List<UserDeviceAuthAddreddDTO> authAddrByDeviceAddrList = new ArrayList<>();
                for (TimeTaskAuthDeviceAddressInfoPO timeTaskAuthDeviceAddressInfoPO : addrPOList) {
                    String unitIds = timeTaskAuthDeviceAddressInfoPO.getUnitId();

                    if (StringUtils.isEmpty(unitIds)){
                        continue;
                    }

                    String[] uniIdArr = unitIds.split(",");
                    Set<String> unitIdSet = new HashSet<>(Arrays.asList(uniIdArr));
                    String authUserId = timeTaskAuthDeviceAddressInfoPO.getAuthUserId();
                    //查找受影响的用户及其地址
                    Map<String, String> addrChangeMap = new HashMap<>();
                    addrChangeMap.put("authUserId", authUserId);
                    //当转换后的unitId地址大于200时，采用全小区更新
                    if (unitIdSet.size() > 200) {
                        addrChangeMap.put("projectId", timeTaskAuthDeviceAddressInfoPO.getProjectId());
                    } else {
                        addrChangeMap.put("unitIds", String.join(",", unitIdSet));
                    }
                    List<UserDeviceAuthAddreddDTO> authAddrByDeviceAddr = iPropertyHouseHoldInfoServiceClient.getAuthAddrByDeviceAddr(addrChangeMap);
                    if (authAddrByDeviceAddr != null && !authAddrByDeviceAddr.isEmpty()) {
                        authAddrByDeviceAddrList.addAll(authAddrByDeviceAddr);
                    }

                    String deviceUniques = timeTaskAuthDeviceAddressInfoPO.getDeviceUniques();
                    if(StringUtils.isNotBlank(deviceUniques)){
                        if(!deviceUniques.contains(",")){
                            String deviceUnique = deviceUniques;
                            List<EquipAuthUserGetVO> list = iPropertyEquipServiceClient.getSmartCardUser(deviceUnique);
                            if(list!=null && list.size()>0){
                                iPropertyDeviceAuthServiceClient.noticeOtherServiceRedisBySamrtCard(list);
                            }
                        }else{
                            String[] deviceUniquesArr = deviceUniques.split(",");
                            for(String deviceUnique : deviceUniquesArr){
                                List<EquipAuthUserGetVO> list = iPropertyEquipServiceClient.getSmartCardUser(deviceUnique);
                                if(list!=null && list.size()>0){
                                    iPropertyDeviceAuthServiceClient.noticeOtherServiceRedisBySamrtCard(list);
                                }
                            }
                        }
                    }


                }

                //刷新用户权限,并且更新定时任务表中的数据状态 由于避免出现处理超时的情况，现对其进行异步处理
                new Thread(() -> {
                    try{
                        iPropertyDeviceAuthServiceClient.updateAddrUserAuthByTimeTask(authAddrByDeviceAddrList, DeviceAuthEnum.DEVICEAUTH_PROPERTY.getType(), handlerTime);
                    } catch (Exception e){
                        throw new DataAccessException("【设备地址变更定时刷新用户权限异常】", e);
                    }
                }).start();
            }
        } catch (Exception e) {
            throw new DataAccessException("【设备地址变更定时刷新用户权限异常】", e);
        } finally {
            deviceAddrChangeFreshAuthFirstStart = false;
            iPropertyDeviceAuthServiceClient.updateDeviceAuthTimeTaskExexuterStatus(false);
        }
    }
}